package com.geen.tuoke.utils;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import com.blankj.utilcode.util.LogUtils;

import static android.content.Context.TELEPHONY_SERVICE;

/**
 * 之前安卓6-8的时候 还可以监听到接通和挂断  现在安卓11不可以了
 * 逻辑修改为：监听挂断后  这个时候就去查询通话记录 获取最新的一条记录
 * 里面有字段表示当前通话的状态【电话号码 通话时间  接通状态等】
 */
public class PhoneStateReceiver extends BroadcastReceiver {

    OnPhoneListener onPhoneListener;
    //拨打电话的标志
    boolean isCallFlag = false;

    public PhoneStateReceiver(OnPhoneListener onPhoneListener) {
        super();
        this.onPhoneListener = onPhoneListener;
    }


    @Override
    public void onReceive(Context context, Intent intent) {

        TelephonyManager telMgr = (TelephonyManager) context.getSystemService(TELEPHONY_SERVICE);
        String number = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);

        if (onPhoneListener == null) {
            return;
        }

        switch (telMgr.getCallState()) {
            case TelephonyManager.CALL_STATE_RINGING:
                if (!TextUtils.isEmpty(number)) {
                    isCallFlag = true;
                    onPhoneListener.onOpen(number);
//                    LogUtils.e(number + "响铃");
                }
                break;
            case TelephonyManager.CALL_STATE_OFFHOOK:
                if (!TextUtils.isEmpty(number)) {
                    onPhoneListener.onOpen(number);
//                    LogUtils.e(number + "接通" + System.currentTimeMillis());
                    isCallFlag = true;
                }

                break;
            case TelephonyManager.CALL_STATE_IDLE:

                if (TextUtils.isEmpty(number)) {
                    if (isCallFlag) {
                        //如果之前是拨打状态 且  电话为空    这个时候就是用户主动挂断了
                        isCallFlag = false;
                        onPhoneListener.onClose();
//                        LogUtils.e(" 空号码  onClose  " + System.currentTimeMillis());
                    }
                } else {
                    if (isCallFlag) {
                        isCallFlag = false;
//                        LogUtils.e(number + "挂断" + System.currentTimeMillis());

                        onPhoneListener.onClose();
                    }

                }
                break;
        }

    }

    public interface OnPhoneListener {
        void onOpen(String phone);

        void onClose();
    }


} 